package com.sunlei.consumer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }


    @Slf4j
    @RestController
    static class TestController {
        @Autowired
        LoadBalancerClient loadBalancerClient;
        // 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
        @GetMapping("/consumer/test1")
        public String test1() {

            ServiceInstance serviceInstance = loadBalancerClient.choose("server");
            String url = serviceInstance.getUri() + "/provider/hello?name=" + "didi";
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.getForObject(url, String.class);
            return "Invoke : " + url + ", return : " + result;
        }


        @Bean
        @LoadBalanced
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }

        @Autowired
        RestTemplate restTemplate;


        // RestTemplate server名直接访问
        @GetMapping("/consumer/test2")
        public String test2() {
            String result = restTemplate.getForObject("http://server//provider/hello?name=ak47", String.class);
            return result;
        }

        @Autowired
        Client client;

        // FeignClient
        @GetMapping("/consumer/test3")
        public String test3() {
            return client.hello("123");
        }
    }


    @FeignClient("server")
    interface Client {
        @GetMapping("/provider/hello")
        String hello(@RequestParam(name = "name") String name);
    }
}
